﻿using System.Runtime.Serialization;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Net;
using System.IO;
using System.Web;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;








namespace H2o
{
    public partial class Main : Form
    {
        RASDisplay ras;
        BrowserPipe browserPipe;
        bool loopControl = true;
        string loginAddress = "http://www.loozo.cn/api/login?u={username}";
        string loginusername = "";
        string isLoginUrl = "http://www.loozo.cn/api/isLogin";
        string logouturl = "http://www.loozo.cn/api/logout?u={username}";
        string scriptAddrs = "http://www.loozo.cn/api/website";

        public Main()
        {
            InitializeComponent();
            ras = new RASDisplay();
            browserPipe = new BrowserPipe(this);
        }
        /// <summary>
        /// 获得脚本json数据
        /// </summary>
        /// <returns></returns>
        private List<String> getJson()
        {
            string jsinstr = Helper.SendRequest(scriptAddrs);
            List<String> websiteList = new List<String>();

            System.Runtime.Serialization.Json.DataContractJsonSerializer _Json =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(websiteList.GetType());
            byte[] _Using = System.Text.Encoding.UTF8.GetBytes(jsinstr);
            System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_Using);
            _MemoryStream.Position = 0;

            return (List<String>)_Json.ReadObject(_MemoryStream);
        }
        /// <summary>
        /// 获得脚本json数据,带用户信息的
        /// </summary>
        /// <returns></returns>
        private List<String> getJson(string userinfo)
        {
            string jsinstr = Helper.SendRequest(scriptAddrs + "?u=" + userinfo);
            List<String> websiteList = new List<String>();

            System.Runtime.Serialization.Json.DataContractJsonSerializer _Json =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(websiteList.GetType());
            byte[] _Using = System.Text.Encoding.UTF8.GetBytes(jsinstr);
            System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_Using);
            _MemoryStream.Position = 0;

            return (List<String>)_Json.ReadObject(_MemoryStream);
        }

        /// <summary>
        /// 获得脚本json数据,带用户信息和读取次数的
        /// </summary>
        /// <returns></returns>
        private List<String> getJson(string userinfo,int loopNumber)
        {
            string jsinstr = Helper.SendRequest(scriptAddrs + "?u=" + userinfo + "&n=" + loopNumber);
            List<String> websiteList = new List<String>();

            System.Runtime.Serialization.Json.DataContractJsonSerializer _Json =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer(websiteList.GetType());
            byte[] _Using = System.Text.Encoding.UTF8.GetBytes(jsinstr);
            System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_Using);
            _MemoryStream.Position = 0;

            return (List<String>)_Json.ReadObject(_MemoryStream);
        }

        /// <summary>
        /// 判断用户是否已经登录
        /// </summary>
        /// <returns></returns>
        private String isLogin(string userinfo)
        {
            string jsinstr = Helper.SendRequest(isLoginUrl + "?u=" + userinfo);

            return jsinstr;
        }

        /// <summary>
        /// 等待几秒种
        /// </summary>
        /// <param name="second"></param>
        private void waitOfSecond(int second)
        {
            for (int x = 0; x < second && loopControl; x++)
            {
                Application.DoEvents();
                Thread.Sleep(1000);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="t"></param>
        /// <param name="level"></param>
        public void log(string t, int level)
        {
            if (Int16.Parse("2") >= level)
            {
                log(t);
            }
        }
        public void log(string t)
        {
            this.logs.AppendText(t + "\r\n");
        }
        private void button2_Click(object sender, EventArgs e)
        {
            loopControl = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            loopControl = false;
            this.status.Text = "停止.";
        }

        /*
        private void updateVersion()
        {
            /////////////////////////
            if (lastTime == 0 || lastTime != DateTime.Now.Day)
            {
                //log("Check Update...");

                string[] str = Helper.SendRequest(this.updateAddr.Text).Split('|');

                if (str.Count() > 1 && str[1].StartsWith("http"))
                {
                    //log("Update...");

                    if (ShouldUpdate(str[0], this.Text))
                    {
                        System.Diagnostics.Process.Start(Application.StartupPath + @"\AutoUpdater.exe",
                            str[1]);
                        this.Close();
                    }
                }
            }

            lastTime = DateTime.Now.Day;
        }
         * */

        private bool ShouldUpdate(string serverVersion, string localVersion)
        {
            if (!string.IsNullOrEmpty(serverVersion) && !string.IsNullOrEmpty(localVersion))
            {
                return serverVersion.CompareTo(localVersion) > 0;
            }
            return true;
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            loopControl = false;
            if (ras != null)
            {
                //ras.Disconnect();
                //if (ras.Connected() == IntPtr.Zero) ras.Connect(this.connName.Text);
                ras = null;
            }
            if (browserPipe != null)
            {
                browserPipe = null;
            }
            Helper.clear();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            MessageBox.Show("IE Version " + Helper.getIEVersion());
        }

        private void Main_Load(object sender, EventArgs e)
        {
            
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (MessageBox.Show("你确认要退出该程序吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                // 删除登录的用户
                string logout = logouturl;
                //log(this.textBox1.Text);
                logout = logout.Replace("{username}", loginusername);
                Helper.SendRequest(logout);
                
                base.OnFormClosing(e);
            }
            else
            {
                e.Cancel = true;
            }
        }  

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Main_Shown(object sender, EventArgs e)
        {
            //start();
        }

        private void timeout_TextChanged(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            string loginurl = loginAddress;
            //log(this.textBox1.Text);
            loginurl = loginurl.Replace("{username}", this.textBox1.Text);
            string loginInfo = Helper.SendRequest(loginurl);
            string[] returnInfo = loginInfo.Split(new   char[]{ '|'});
            if (returnInfo.Length > 1)
            {
                loginusername = returnInfo[1];
                this.button6.Hide();
                this.button7.Show();
                string s = Helper.GetMacAddress();



                this.label13.Text = "登录成功..." + s;
            }
            else {
                this.label13.Text = returnInfo[0];
            }
        }

        int threadNumber = 0;
        private void button7_Click_1(object sender, EventArgs e)
        {
            int accessError = 0;
            int loopNumber = 0;
            this.button7.Enabled = false;
            
            Boolean isContinue = true;
            try
            {

                if (isLogin(loginusername) == "1")
                {
                    this.label13.Text = "开始读取数据...";
                }
                else {
                    this.label13.Text = "请重新登录...";
                    this.button7.Enabled = true;
                    this.button6.Show();
                    this.button7.Hide();
                    isContinue = false;
                }
                while (isContinue)
                {
                    /// 5，执行脚本
                    //Application.DoEvents();
                    
                    accessError = 0;
                    List<String> script = getJson(loginusername,loopNumber);

                    //log("Scripts Total : " + script.Count + " Time Now = " + DateTime.Now.ToLongTimeString());
                    Console.WriteLine("script.Count==" + script.Count);
                    if (script.Count == 1) {
                        string[] returnInfo = script[0].Split(new char[] { ',' });
                        if (returnInfo[0] == "sleep") {
                            if (loopNumber > 0)
                            {
                                this.label13.Text = "刷站完毕！";
                                isContinue = false;
                                this.button7.Enabled = true;
                                break;
                            }
                            else
                            {
                                this.label13.Text = "当前没有可刷站点，请过XX小时后再试！";
                                isContinue = false;
                                this.button7.Enabled = true;
                                break;
                            }
                        }
                    }
                    for (int i = 0; i < script.Count; i++)
                    {
                        //log("Execute Script NO : " + (i + 1));
                        //log(script[i], 2);
                        Thread[] thread = new Thread[script.Count]; 

                        string scriptStr = script[i];
                        Console.WriteLine("scriptStr==" + scriptStr);
                        thread[i] = new Thread(new ParameterizedThreadStart(ThreadRunMethod));
                        thread[i].Start(scriptStr);
                        
                        //process(scriptStr,script.Count);
                    }

                    while (true) {
                        Thread.Sleep(5000);
                        if (threadNumber >= script.Count)
                        {
                            threadNumber = 0;
                            break;
                        }
                    }
                    if (script.Count < 10)
                    {
                        this.label13.Text = "所有站点刷新完毕...";
                        isContinue = false;
                        this.button7.Enabled = true;
                        break;
                    }
                    script.Clear();
                    script = null;
                    loopNumber++;
                    
                    this.label13.Text = "第一部分完成，等待5秒后继续...";
                    Thread.Sleep(3000); 
                }
                //accessError = 0;//成功执行完脚本，就初始化访问错误值
            }
            catch (Exception ee)
            {
                //log(ee.ToString(), 3);
                this.button7.Enabled = true;
                accessError++;
            }
        }

        public void ThreadRunMethod(object script)
        {
            List<BrowserAction> task = Helper.executeScript(script as string);
            if (task == null || task.Count == 0)
            {
                Console.WriteLine("task == null || task.Count == 0 "); 

            }
            if (task.Count == 1)
            {
                //this.label13.Text = "not task ,so sleep...";
                Console.WriteLine("task.Count == 1"); 

            }
            //Thread t = new Thread(new ThreadStart(ThreadProc));
            //t.Start(); 
            browserPipe.process(task);
            task.Clear();
            task = null;
            threadNumber = threadNumber + 1;
            Application.DoEvents();
        }

    }
}
